'''
Created on 23/09/2010

@author: fccoelho
'''

import os
import pickle

from google.appengine.ext import webapp
from google.appengine.ext.webapp import util
from google.appengine.ext.webapp.util import login_required
from google.appengine.api import users
from google.appengine.ext.webapp import template
from models import *

openIdProviders = (
    ('Gmail.com','images/google.png'), # shorter alternative: "Gmail.com"
    ('Yahoo.com','images/yahoo.png'),
    ('MySpace.com','images/myspace.png'),
    ('AOL.com','images/aol.png'),
    ('Flickr.com','images/flickr.png'),
    ('Wordpress.com','images/wordpress.png')
    # add more here
)


class MainHandler(webapp.RequestHandler):
    '''main page'''
    def get(self):
        if users.get_current_user():
            q = Member.all().filter('user =', users.get_current_user())
            if not q.get():#if user is not yet a member
                u = Member(user=users.get_current_user())
                u.put()
            url = users.create_logout_url(self.request.uri)
            url_linktext = 'Logout'
            logged_in = 1
            providers = []
            #TODO: add to members table if not there yet
        else:
            providers = [(users.create_login_url(dest_url="/",federated_identity=url[0].lower()),url[1]) for url in openIdProviders]
            url = users.create_login_url(self.request.uri)
            url_linktext = 'Login'
            logged_in = 0

        template_values = {
            'url': url,
            'url_linktext': url_linktext,
            'logged_in': logged_in,
            'providers':providers #login urls and images
            }

        path = os.path.join(os.path.dirname(__file__), 'templates/base.html')
        self.response.out.write(template.render(path, template_values))
    
class Profile(webapp.RequestHandler):
    """
    Registration page
    """
    @login_required
    def get(self):
        self.response.out.write('This is the mock Profile page!')

class Library(webapp.RequestHandler):
    '''
    Model Library page
    '''
    def get(self):
        u = users.get_current_user()
        models = Document.all().order('name').fetch(100)
        template_values = {
                'models':models,
                           }
        path = os.path.join(os.path.dirname(__file__), 'templates/library.html')
        self.response.out.write(template.render(path, template_values))

class TAW(webapp.RequestHandler):
    '''
    Renders the Document presentation page
    '''
    @login_required
    def get(self):
        if 'docid' in self.request.arguments():
            mid = self.request.get('docid')
            doc = Document.get(mid)
            template_values = {
                'docname': doc.name,
                'eqlist':[],
                'parlist':[]
                               }
        else:
            template_values = {}
        path = os.path.join(os.path.dirname(__file__), 'templates/workbench.html')
        self.response.out.write(template.render(path, template_values))

    
    def post(self):
        '''
        Handle Document uploads
        '''
        u = users.User(self.request.get('owner'))
        mn = self.request.get('name')
        aut = Member.all().filter('user =', u).get()
        src = pickle.loads(self.request.get('source'))
        pub = bool(int(self.request.get('public')))
        mo = Document.all().filter('owner =', aut).filter('name =', mn).get()
        if not mo:
            mo = Document(name=mn,author=aut,source=src,public=pub)
        else:
            mo.name = nm
            mo.owner = aut
            mo.source = src
            mo.public = pub
        mo.put()
        


class About(webapp.RequestHandler):
    def get(self):
        ninst = Install.all().count()
        finst = Install.all().order('date').get()
        nusers = Member.all().count()
        huse = sum([s.duration for s in Session.all()])/3600.
        if not finst:
            fdate =None
        else:
            fdate = finst.date
        
        template_values = {
            'ninst': ninst,
            'fdate': fdate,
            'nusers': nusers,
            'huse': huse
            }

        path = os.path.join(os.path.dirname(__file__), 'templates/about.html')
        self.response.out.write(template.render(path, template_values))

class Search(webapp.RequestHandler):
    def post(self):
#        print "busca %s"%self.request.get('q')
        self.redirect('/taw')

class Verify(webapp.RequestHandler):
    '''Returns 1 or 0 according to whether the userid is registered''' 
    def post(self):
        id = self.request.get('userid')
        u = users.User(id)
        M = Member.all().filter('user =',u).get()
        if M:
            self.response.out.write('1')
            return
        self.response.out.write('0')
        
class SetLocation(webapp.RequestHandler):
    def post(self):
        u = users.get_current_user()
        if not u:
            return
        m = Member.all().filter('user =', u).get()
        lat = float(self.request.get('lat'))
        lon = float(self.request.get('lon'))
        m.location = db.GeoPt(lat,lon)
        m.put()
        
def model_parse(src, model):
    '''
    Parses the model source and returns a dictionary
    '''
    pass



def main():
    application = webapp.WSGIApplication([('/', MainHandler),
                                          ('/profile', Profile),
                                          ('/library',Library),
                                          ('/search',Search),
                                          ('/about', About),
                                          ('/verify',Verify),
                                          ('/taw',TAW),
                                          ('/setlocation',SetLocation),],
                                         debug=True)
    util.run_wsgi_app(application)
    
if __name__ == '__main__':
    pass